import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import React, { useState, useEffect, FC } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
interface IWangEditorProps {
  value?: string;
  onChange?: (html: string) => void;
}
const WangEditor: FC<IWangEditorProps> = (props) => {
  const { value, onChange } = props;
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法                 // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState<string>(value || "<p>请输入编辑内容</p>");

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: "请输入日志内容...",
    MENU_CONF: {
      // 上传图片的配置
      uploadImage: {
        server:
          "https://www.fastmock.site/mock/00b00005835f7faef03bc3481337da3b/testFast/api/image/upload",
        fieldname: "file",
        fileType: ["image/png", "image/jpeg", "image/gif", "image/jpg"],
        base64LimitSize: 5000 * 1024, //大于5kb才上传
      },
    },
    onCreated: (editor) => {
      setEditor(editor);
    },
    onChange: (editor) => {
      const html = editor.getHtml();
      setHtml(html);
      onChange && onChange(html);
    },
    onDestroyed: () => {
      setEditor(null);
    },
  };
  useEffect(() => {
    value && setHtml(value); //如果值变化的话 编辑器的值也要及时变化
  }, [value]);

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => onChange && onChange(editor.getHtml())}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
    </>
  );
};
// 默认赋值
WangEditor.defaultProps = {
  value: "",
  onChange: () => {},
};
export default WangEditor;
